//
//  CateViewController.m
//  悠狸
//
//  Created by dlios on 15-8-27.
//  Copyright (c) 2015年 Dung. All rights reserved.
//

#import "CateViewController.h"
#import "CateCell.h"
#import "Asyn.h"
#import "Tools.h"
#import "CateModel.h"
#import "URL.h"
#import "CateHeaderView.h"
#import "SpecialCell.h"
#define Width self.view.frame.size.width
#define Height self.view.frame.size.height

#import "MainCategories.h"
#import "SecondCategories.h"
#import "MainView.h"
#import "CategoryCollectionViewController.h"
#import "SpecialViewController.h"
#import "CircleViewController.h"
#import "SpecialDetailsViewController.h"
#import "GiftTableViewCell.h"

#define ScrollRightTag 20


@interface CateViewController ()<UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate,MainViewDelegate,CateCellDelegate,SpecialCellDelegate>

@property (nonatomic ,retain)UISegmentedControl *segmentedControl;
@property (nonatomic, retain)UIScrollView *scroll;
@property (nonatomic, retain)NSMutableArray *array;

@property (nonatomic, retain)NSMutableArray *cateArr;
@property(nonatomic, retain)NSMutableArray *arrayArr;
//@property (nonatomic, retain)NSMutableArray *scrollarr;

@property (nonatomic, retain)UITableView *table;


// 右侧
@property (nonatomic, retain)UITableView *tableLeft;
@property (nonatomic, retain)UIScrollView *scrollRight;

@property (nonatomic, retain)NSMutableArray *leftTableArray;
@property (nonatomic, retain)NSMutableArray *rightArray;
@property (nonatomic, assign)CGFloat allHeight;
@property (nonatomic, retain)NSMutableArray *heighArray;


@end

@implementation CateViewController

- (void)dealloc
{
    
    
    [_table release];
    [_segmentedControl release];
    [_array release];
    [_cateArr release];
    [_arrayArr release];
//    [_scroll release];

    [_leftTableArray release];
    [_rightArray release];
    [_heighArray release];
    [_scrollRight release];
    [_tableLeft release];

    [super dealloc];
}
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.array = [NSMutableArray array];
//        self.scrollarr = [NSMutableArray array];
        self.cateArr = [NSMutableArray array];
        self.arrayArr = [NSMutableArray array];

        self.leftTableArray = [NSMutableArray array];
        self.rightArray = [NSMutableArray array];
        self.heighArray = [NSMutableArray array];

    }
    return self;
}
#pragma mark-分割
- (void)viewDidLoad {
     
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
     self.navigationController.navigationBar.barTintColor = [UIColor orangeColor];
    
    NSArray *arr = @[@"攻略", @"礼物"];
    self.segmentedControl = [[UISegmentedControl alloc] initWithItems:arr];
    _segmentedControl.tintColor = [UIColor whiteColor];
    self.navigationItem.titleView = _segmentedControl;

    _segmentedControl.selectedSegmentIndex= 0;
    
    [_segmentedControl addTarget:self action:@selector(tap:) forControlEvents:UIControlEventValueChanged];
    
    [self createscroll];
    [self createtable];
    
    [self parser];
    [self cateparser];
    [self connect1];
    
}
#pragma mark---分类里,礼物页面,分割右面
- (void)connect1
{
    
    [Asyn  startParser:LY_LY partemer:nil file:@"data6" block:^(NSData *data) {
        
        //存储
        [Tools toolsOfSaveLibraryPathName:@"data6" data:data];
        // 解析
        NSDictionary *dic = [Tools toolsOfJsonDataType:dicType fileName:@"data6"];

         NSDictionary *dic1 =[dic objectForKey:@"data"];
         NSArray *arrayCategory = [dic1 objectForKey:@"categories"];
         
         for (NSDictionary *dic in arrayCategory) {
             MainCategories *mainC = [[MainCategories alloc] initWithDic:dic];
             [_leftTableArray addObject:mainC];         }
         [self.tableLeft reloadData];
         
         self.allHeight = 0;
         
         // 创建scroll中得View
         for (int i = 0; i < [arrayCategory count]; i++) {
             MainCategories *mainC = _leftTableArray[i];
//             NSLog(@"MainCategories = %@", mainC.subcategories);
             
             CGFloat y = self.allHeight ;
             CGFloat width = self.scrollRight.frame.size.width;
             CGFloat heigh = ((mainC.subcategories.count - 1) / 3 +1) * 100*OffHeight + 40*OffHeight;
             UIView *scrollView = [[UIView alloc] initWithFrame:CGRectMake(0, y, width, heigh*OffHeight)];
//             scrollView.backgroundColor = [UIColor yellowColor];
             UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, 20*OffHeight)] autorelease];
             label.font = [UIFont systemFontOfSize:15];
          
             NSString *nameS = [NSString stringWithFormat:@"----------- %@ -----------", mainC.name];
             
             [label setText:nameS];
             [label setTextAlignment:NSTextAlignmentCenter];
             [scrollView addSubview:label];
             // 创建右边试图(小视图)
             NSArray *array = mainC.subcategories;
             for (int i = 0; i<[array count]; i++) {
                 CGFloat btnY = (20*OffHeight + i / 3 * 100*OffHeight);
                 CGFloat btnWidth = ((width-30*OffWidth)/3) ;
                 CGFloat btnX = (i%3 * btnWidth + i%3 * 15*OffWidth);
                 CGFloat btnHeigh = 90*OffHeight;
                 MainView *btn = [[MainView alloc] initWithFrame:CGRectMake(btnX, btnY, btnWidth, btnHeigh)];
                 SecondCategories *sec = [[SecondCategories alloc] initWithDic:array[i]];
                 [btn sendSecCategory:sec];
                 btn.delegate = self;
//                 btn.backgroundColor = [UIColor cyanColor];
                 [scrollView addSubview:btn];
             }
             scrollView.tag = 100 + i;
             [self.scrollRight addSubview:scrollView];
             NSNumber *hei = [[NSNumber alloc] initWithFloat:self.allHeight];
             [self.heighArray addObject:hei];
             self.allHeight = heigh + self.allHeight;
         }
         
         [self.scrollRight setContentSize:CGSizeMake(0, self.allHeight)];
     }];
}

#pragma mark - btnDelegate右边,分类,礼物详情
- (void)didSelectedMainViewWithSecondCategory:(SecondCategories *)secondCategories
{
    //传数据
    NSLog(@"点击了 second name = %@", secondCategories.name);
    CategoryCollectionViewController *cateGoryVC = [[CategoryCollectionViewController alloc] init];
    cateGoryVC.secondCategory = secondCategories;// 根据里面的id 进行网络请求
    cateGoryVC.title = secondCategories.name ;
    // 根据
    [self.navigationController pushViewController:cateGoryVC animated:YES];
}
#pragma mark-最下层scroll
- (void)createscroll
{
    self.scroll = [[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height- 49 )] autorelease];
    _scroll.pagingEnabled = YES;
    _scroll.contentSize = CGSizeMake(self.view.frame.size.width *2, 0);
    _scroll.contentOffset = CGPointMake(0, 0);
    
    self.view.backgroundColor = [UIColor whiteColor];
    _scroll.delegate =self;
    [self.view addSubview:_scroll];
    

    // 创建scroll的右半部分
    [self makeRight];
}
#pragma mark---右半边视图(左半边是table,右边是scroll)
- (void)makeRight
{
    CGFloat x = self.view.frame.size.width;
    CGFloat y = 64 *OffHeight;
    CGFloat width = 90;
    CGFloat height = 400*OffHeight;
    _tableLeft = [[UITableView alloc] initWithFrame:CGRectMake(x, y, width, height) style:UITableViewStyleGrouped];
    _tableLeft.tag = 10;
    _tableLeft.delegate = self;
    
    _tableLeft.dataSource = self;
    self.navigationController.automaticallyAdjustsScrollViewInsets = YES;
    
    [_scroll addSubview:_tableLeft];
    
    _scrollRight = [[UIScrollView alloc] initWithFrame:CGRectMake(x+width + 5, y, x-width, height)];
    [_scroll addSubview:_scrollRight];
  
    _scrollRight.delegate = self;
    _scrollRight.tag = ScrollRightTag;
}
#pragma mark---左大半边tableview
- (void)createtable
{
    _table =[[[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.scroll.frame.size.width, self.scroll.frame.size.height - 49) style:UITableViewStylePlain] autorelease];
    _table.delegate = self;
    _table.dataSource =self;
   
    [_scroll addSubview:_table];
    
    [_table registerClass:[SpecialCell class] forCellReuseIdentifier:@"d"];
    [_table registerClass:[CateCell class] forCellReuseIdentifier:@"e"];
    
    [_tableLeft registerClass:[UITableViewCell class] forCellReuseIdentifier:@"j"];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
#pragma mark---右边视图(左半边table)
    if (tableView.tag == 10) {
        return 44*OffHeight;
    }
    if (indexPath.row ==0) {
        return 180*OffHeight;
    }
    if (indexPath.row == 1) {
        return 340*OffHeight;
    }else{
        return 240*OffHeight;
    }
   
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (tableView.tag == 10) {
        return [self.leftTableArray count];
        
    }else{
        if (_array.count > 0) {
            
            return 1 + _cateArr.count ;
        }
        else{
            return 0;
        }
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (tableView.tag == 10) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"j" forIndexPath:indexPath];
        
        MainCategories *cate = self.leftTableArray[indexPath.row];
        cell.textLabel.text = cate.name;
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        cell.textLabel.font = [UIFont systemFontOfSize:13];
        cell.textLabel.textColor = [UIColor darkGrayColor];
        
        return cell;
    } else{
    
    
    if (indexPath.row == 0) {

            SpecialCell *cell = [tableView dequeueReusableCellWithIdentifier:@"d"forIndexPath:indexPath];
            CateModel *model = [_array objectAtIndex:indexPath.row];
        [cell sendModel:model NSMutableArray:self.array];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.delegate =self;
        return cell;
        
    } else {
        
   CateCell *cell = [tableView dequeueReusableCellWithIdentifier:@"e"forIndexPath:indexPath];
        
   cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
        [cell sendModel:[_cateArr objectAtIndex:indexPath.row-1]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.dele = self;
    return cell;
        
    } }
    return nil;
 
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSNumber *hei = _heighArray[indexPath.row];
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [UIView animateWithDuration:1 animations:^{
        _scrollRight.contentOffset = CGPointMake(0, hei.doubleValue);
        
    }];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView.tag == ScrollRightTag) {
        scrollView.userInteractionEnabled = NO;
        
    }
}

// 停止滚动
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    
    if (scrollView.tag == ScrollRightTag) {
        // 判断
        CGFloat first = 0;
        CGFloat last = _allHeight;
        NSInteger row = 0;
        
        for (NSInteger i = 0; i < [_heighArray count] - 1; i++) {
            
            NSNumber *one = _heighArray[i];
            NSNumber *two = _heighArray[i+1];
            first = [one floatValue];
            last = [two floatValue];
            if (scrollView.contentOffset.y > first && scrollView.contentOffset.y < last) {
                row = i;
                continue;
            }
        }
        NSIndexPath *path = [NSIndexPath indexPathForRow:row inSection:0];
        [_tableLeft selectRowAtIndexPath:path animated:YES scrollPosition:UITableViewScrollPositionTop];
        
    }else{
        [UIView animateWithDuration:1 animations:^{
            _segmentedControl.selectedSegmentIndex = scrollView.contentOffset.x / self.scroll.frame.size.width;
        }];
    }
    
    scrollView.userInteractionEnabled = YES;
    
}


#pragma mark - 偏移量

- (void)tap:(UISegmentedControl *)seg
{
    
    self.scroll.contentOffset = CGPointMake(seg.selectedSegmentIndex *self.scroll.frame.size.width, 0);
}
#pragma 专题解析
//http://api.liwushuo.com/v2/collections?limit=10&offset=0
- (void)parser
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:@"10" forKey:@"limit"];
    [dic setValue:@"0" forKey:@"offset"];
    
    [Asyn  startParser:Cate_ZT partemer:dic file:@"data7" block:^(NSData *data) {
        
        //存储
        [Tools toolsOfSaveLibraryPathName:@"data7" data:data];
        // 解析
        NSDictionary *dic = [Tools toolsOfJsonDataType:dicType fileName:@"data7"];
        
        NSDictionary *dic1 =[dic objectForKey:@"data"];
        
        NSArray *arr = [dic1 objectForKey:@"collections"];
        
        
        for (NSDictionary *dic2 in arr) {
            CateModel *model = [[[CateModel alloc] init] autorelease];
          
            [model setValuesForKeysWithDictionary:dic2];
            
//            [_scrollarr addObject:model];
            [_array addObject:model];
        }
        [_table reloadData];
//        [self setScrollValue];
    }];
}
//- (void)setScrollValue
//{
//    
//   CateHeaderView*view = [[CateHeaderView alloc] initWithFrame:CGRectMake(0, 0, Width , 110) array:self.scrollarr];
//    _table.tableHeaderView = view;
//}

#pragma mark-品类解析
//http://api.liwushuo.com/v2/channel_groups/all
- (void)cateparser
{

    [Asyn  startParser:Cate_PL partemer:nil file:@"data8" block:^(NSData *data) {
        
        //存储
        [Tools toolsOfSaveLibraryPathName:@"data8" data:data];
        // 解析
        NSDictionary *dic = [Tools toolsOfJsonDataType:dicType fileName:@"data8"];

         NSDictionary *dic1 =[dic objectForKey:@"data"];
        NSArray *array = [dic1 objectForKey:@"channel_groups"];
        for (int i = 0 ; i < array.count ;i++) {
            NSDictionary *dd = [array objectAtIndex:i];
            CateModel *model = [[CateModel alloc]init];
            [model setValuesForKeysWithDictionary:dd];
            [self.cateArr addObject:model];
            
            [model release];
            
        }
        [_table reloadData];
    }];
    
}
- (void)sendCate:(CateModel *)model
{
    
    CircleViewController *circle = [[[CircleViewController alloc] init] autorelease];
    
    circle.cate = model;
    
    [self.navigationController pushViewController:circle animated:YES];
    
}
#pragma mark---回调button方法
- (void)sendButton
{
    SpecialViewController *special = [[[SpecialViewController alloc] init] autorelease];
    
    [self.navigationController pushViewController:special animated:YES];
    
}
#pragma mark---回调专题(collectionitem)方法
- (void)sendValue:(CateModel *)cate array:(NSMutableArray *)array
{
     SpecialDetailsViewController  *spe = [[[SpecialDetailsViewController alloc] init] autorelease];
    spe.catemodel =cate;
    spe.catearray = array;
    [self.navigationController pushViewController:spe animated:YES];
}

@end
